package com.nsqt.system.controller;

import com.nsqt.common.annotation.Log;
import com.nsqt.common.controller.BaseController;
import com.nsqt.common.domain.FileDO;
import com.nsqt.common.domain.Tree;
import com.nsqt.common.service.FileService;
import com.nsqt.common.utils.MD5Utils;
import com.nsqt.common.utils.Query;
import com.nsqt.common.utils.R;
import com.nsqt.common.utils.ShiroUtils;
import com.nsqt.system.domain.MenuDO;
import com.nsqt.system.domain.UserDO;
import com.nsqt.system.service.MenuService;
import com.nsqt.system.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class LoginController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    MenuService menuService;
    @Autowired
    UserService userService;
    @Autowired
    FileService fileService;
    @Value("${server.sysname}")
    private String sysName;

    @GetMapping({"/", ""})
    String welcome(Model model) {

        return "redirect:/blog";
    }

    @Log("请求访问主页")
    @GetMapping({"/index"})
    String index(Model model) {
        List<Tree<MenuDO>> menus = menuService.listMenuTree(getUserId());
        model.addAttribute("menus", menus);
        model.addAttribute("name", getUser().getName());
        FileDO fileDO = fileService.get(getUser().getPicId());
        if (fileDO != null && fileDO.getUrl() != null) {
            if (fileService.isExist(fileDO.getUrl())) {
                model.addAttribute("picUrl", fileDO.getUrl());
            } else {
                model.addAttribute("picUrl", "/img/photo_s.jpg");
            }
        } else {
            model.addAttribute("picUrl", "/img/photo_s.jpg");
        }
        model.addAttribute("username", getUser().getUsername());
        model.addAttribute("sysName", sysName);
        return "index";
    }


    @GetMapping("/login")
    String login(Model model) {
        model.addAttribute("sysName", sysName);
        return "login";
    }

    /**
     * 检查远程用户登录接口
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/checkuser")
    public String checkUser(HttpServletRequest request, HttpServletResponse response) {

        String user = request.getParameter("user");
        String password = request.getParameter("password");
        password = MD5Utils.encrypt(user, password);

        //查询列表数据
        Map map = new HashMap();
        map.put("limit", 10);
        map.put("offset", 20);
        map.put("username", user);
        map.put("password", password);
        Query query = new Query(map);
        query.remove("page");
        //List<UserDO> users = userService.list(query);
        UserDO currUser = userService.getByUserName(query);
        if (currUser != null) {
            return currUser.getUserId().toString();
        } else {
            return "no";

        }
    }

    @Log("登录")
    @PostMapping("/login")
    @ResponseBody
    R ajaxLogin(String username, String password) {

        password = MD5Utils.encrypt(username, password);
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            return R.ok();
        } catch (AuthenticationException e) {
            return R.error("用户或密码错误");
        }
    }

    @GetMapping("/logout")
    String logout() {
        ShiroUtils.logout();
        return "redirect:/login";
    }


    @GetMapping("/main")
    String main() {
        return "main";
    }

}
